<!-- 数据订单页 -->
<template>
  <div>
    <!-- <header class="header">
      <a-button @click="serverSettings" ghost type="primary" size="small">
        <span>服务器设置</span>
      </a-button>
      <a-button @click="submitFile" ghost type="primary" size="small" style="margin: 0 5px;">
        <span>上传本地文件</span>
      </a-button>
      <a-button @click="submitDirectory" ghost type="primary" size="small">
        <span>上传本地目录</span>
      </a-button>
    </header> -->
    <a-table :columns="($customer === 'zhy' ? columnsHY : columnsXN).filter((col) => {
      return col.show;
    })
      " :data-source="dataSource" :scroll="{ y: windowHeight - 150, scrollToFirstRowOnChange: true }" :pagination="{
    position: ['bottomRight'],
    defaultPageSize: pageInfo.pageSize,
    total: total,
    current: pageInfo.currentPage,
    showQuickJumper: true,
    hideOnSinglePage: false,
    showTotal: (total, range) => ` 共 ${total} 条数据`,
  }" @change="onChange" @resizeColumn="handleResizeColumn" :loading="loading" rowKey="orderId" size="small"
      class="ks-table">
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'index'">
          {{ (pageInfo.currentPage - 1) * pageInfo.pageSize + index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'approveProcess'">
          <!-- 查看审批流程 -->
          <a @click="viewProcess(record)">查看</a>
        </template>
        <template v-if="column.dataIndex === 'dataitem'">
          <!-- 查看数据项清单 -->
          <a v-if="$customer !== 'zhy' || record.hasDataItem === true" @click="viewDataItems(record)">查看</a>
          <div v-else>--</div>
        </template>
        <template v-if="column.dataIndex === 'cuttingTask'">
          <!-- 查看切割任务 -->
          <a v-if="$customer !== 'zhy' || record.hasSplitItem === true" @click="viewCuttingTask(record)">查看</a>
          <div v-else>--</div>
        </template>
        <!-- 下载操作 -->
        <template v-if="column.dataIndex === 'download'">
          <a @click="handleDownload(record)">下载</a>
        </template>
      </template>
    </a-table>

    <!-- 服务器设置 -->
    <serverSettings v-if="isshowServerSetting" @close="dialogClose" list="directory" @submitY="submitY"></serverSettings>

    <!-- 查看数据清单 -->
    <dialog-download-items v-if="dialogVisible" :abledownload="abledownload" :orderId="orderId" @close="dialogClose"
      :orderName="orderName" />

    <!-- 切割数据 -->
    <DataCuttingDrawer v-if="cuttingTask" @close="dialogClose" :id="id" :orderName="orderName" :orderId="orderId">
    </DataCuttingDrawer>
  </div>
</template>

<script>
import { DataTableMixin } from "@/mixins/DataTableMixin";
import serverSettings from './components/ServerSettings.vue'
import DialogDownloadItems from "./components/DialogViewItems.vue";
import { fileSelect, addUploadGRPC } from '@/api/grpcLoad'
import DataCuttingDrawer from "./components/DataCuttingDrawer.vue";
import {
  getDownloadableItems,
  downloadDataItem,
  getDownloadableList_HY,
  getDownloadableList_XN
} from "@/api/dataDownloadPublish";
import { message } from "ant-design-vue";
export default {
  name: "DownloadableOrder",
  mixins: [DataTableMixin],
  components: {
    serverSettings,
    DialogDownloadItems,
    DataCuttingDrawer
  },
  data() {
    return {
      isshowServerSetting: false,
      loading: false,
      // 分页信息
      total: 0,
      orderId: 0,
      orderName: "",
      fuType: '',
      ftid: 0,
      dialogfuVisible: false,
      dialogVisible: false,
      abledownload: "",
      cuttingTask: false,
      id: null,
      // 表头(海油)
      columnsHY: [
        { title: "id", dataIndex: "id", show: false },
        {
          title: "序号",
          dataIndex: "index",
          width: 50,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "订单名称",
          dataIndex: "orderName",
          width: 150,
          align: "center",
          resizable: true,
          show: true,
        },
        {
          title: "申请人",
          dataIndex: "nickName",
          width: 100,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "数据项",
          dataIndex: "dataitem",
          align: "center",
          width: 70,
          show: true,
          resizable: true,
        },
        {
          title: "切割任务",
          dataIndex: "cuttingTask",
          align: "center",
          width: 100,
          show: true,
        },
        {
          title: "申请时间",
          dataIndex: "ctime",
          width: 130,
          ellipsis: true,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "更新时间",
          dataIndex: "etime",
          width: 130,
          ellipsis: true,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "审批状态",
          dataIndex: "stateName",
          width: 100,
          align: "center",
          ellipsis: true,
          show: true,
          resizable: true,
        },
        {
          title: "审批流程",
          dataIndex: "flowName",
          align: "center",
          width: 100,
          show: true,
          resizable: true,
        },
      ],
      // 表头(西南)
      columnsXN: [
        {
          title: "序号",
          dataIndex: "index",
          width: 50,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "订单ID",
          dataIndex: "orderId",
          width: 80,
          align: "center",
          show: false,
          resizable: true,
        },
        {
          title: "申请人",
          dataIndex: "applicant",
          width: 100,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "数据项",
          dataIndex: "dataitem",
          align: "center",
          width: 80,
          show: true,
          resizable: true,
        },
        {
          title: "申请时间",
          dataIndex: "applyDate",
          width: 130,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "初审人",
          dataIndex: "approver1",
          width: 100,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "初审时间",
          dataIndex: "examineApproveDate1",
          width: 130,
          align: "center",
          show: true,
          resizable: true,
        },
        {
          title: "初审备注",
          dataIndex: "examineApproveRemark1",
          align: "center",
          width: 80,
          ellipsis: true,
          show: true,
          resizable: true,
        },
        {
          title: "初审状态",
          dataIndex: "examineApproveStateStr1",
          width: 80,
          align: "center",
          show: true,
          resizable: true,
        },
        // {
        //   title: "复审流程",
        //   dataIndex: "approveProcess",
        //   align: "center",
        //   width: 130,
        //   show: true,
        //   resizable: true,
        // },
        // {
        //   title: "操作",
        //   dataIndex: "download",
        //   align: "center",
        //   width: 80,
        //   show: true,
        // },
      ],
      dataSource: [],
      // 上传文件参数
      uploadParams: {
        srcpath: null, // 选择的文件或目录的路径
        destdir: 'F:/FileShare/veldep', // 服务器设置: 接收的路径
        destname: '111', // 服务器设置：接收的名称
        checkDestMethod: 0, // 0，1，2，3
        md5: true, // 是否MD5加密 boolean
        destServer: '127.0.0.1', // 服务器地址
        transMethod: 0, // 服务器设置：传输方式 0,1
        priority: 0 // 优先级 0，1，5，9
      }
    }
  },
  methods: {
    viewCuttingTask(record) {
      this.id = record.id
      this.orderId = record.orderId
      this.orderName = record?.orderName
      this.cuttingTask = true
    },
    // 接收服务器设置参数
    submitY(payload, fileName) {
      this.uploadParams.destdir = payload.newPath + fileName[0]
      this.uploadParams.destname = fileName[0]
      this.uploadParams.destServer = payload.serverIP + ':' + payload.serverPort
      // this.uploadParams.transMethod = payload.newPath, // 1,2,3 需要修改
      this.uploadParams.transMethod = 1 // grpc要 0,1
      console.log('999', this.uploadParams)
    },
    // 服务器设置对话框
    serverSettings() {
      this.isshowServerSetting = true
    },
    // 上传本地文件
    async submitFile() {
      try {
        const res = await fileSelect('file')
        console.log('获取文件路径数组', res)
        this.uploadParams.srcpath = res[0]
        this.addUploadUse()
      } catch (error) {
        console.log('error', error)
      }
    },
    // 上传本地目录
    async submitDirectory() {
      try {
        const res = await fileSelect('directory')
        console.log('获取目录数组', res)
        // this.uploadParams.srcpath = 'F:/testdata/SEGY/道集'
        this.uploadParams.srcpath = res[0]
        this.addUploadUse()
      } catch (error) {
        console.log('error', error)
      }
    },
    // 开始上传文件
    async addUploadUse() {
      try {
        const res = await addUploadGRPC(JSON.parse(JSON.stringify(this.uploadParams)))
        console.log('上传文件成功', res)
      } catch (error) {
        console.log('error', error)
      }
    },
    // 查看审批流程
    viewProcess(record) {
      console.log('record', record);
    },
    // 查看订单数据项
    viewDataItems(record) {
      this.orderId = record.orderId;
      this.orderName = record?.orderName || "订单_" + this.orderId
      this.dialogVisible = true;
      this.abledownload = "able";
    },
    // 获取列表
    async getList() {
      try {
        this.loading = true;
        let res
        if (this.$customer === 'zhy') {
          res = await getDownloadableList_HY(this.pageInfo)
        } else {
          res = await getDownloadableList_XN(this.pageInfo)
        }
        console.log('res', res)
        if (res) {
          this.dataSource = this.$customer === 'zhy' ? res?.data : res?.list ?? [];
          // 页码信息
          this.pageInfo = {
            currentPage: res.currentPage,
            pageSize: res.pageSize,
          };
          this.total = res.totalSize;
        }
      } finally {
        this.loading = false;
      }
    },
    // 下载操作
    handleDownload(record) {
      this.orderId = record.orderId;
      // 获取该订单关联的数据项ID
      getDownloadableItems({ orderId: this.orderId }).then((res) => {
        if (res && res.length > 0) {
          console.log('res', res)
          // 下载数据项
          downloadDataItem({ itemId: res }).then((downloadItems) => {
            if (downloadItems && Object.keys(downloadItems).length > 0) {
              // 获取下载链接数组（返回的数：key为下载链接、value为文件名)
              let downloadUrls = Object.keys(downloadItems);
              downloadUrls.forEach((url) => {
                if (url !== "") {
                  // window.open(url);
                  console.log('url', url)
                } else {
                  message.warning("下载失败，可能是未获取到文件");
                }
                // if (res !== "") {
                //   // let url = `${
                //   //   location.href.split("#")[0]
                //   // }api/dataMana/fileStream?filePath=${res}`;
                //   let url = res;
                //   let _form = document.createElement("form");
                //   document.body.append(_form);
                //   _form.method = "POST";
                //   _form.action = url;
                //   _form.target = "_blank";
                //   _form.submit();
                //   _form.remove();
                // } else {
                //   
                // }
              });
            }
          });
        }
      });
    },
    // 关闭服务器设置对话框
    dialogClose() {
      this.isshowServerSetting = false
      this.dialogVisible = false;
      this.cuttingTask = false
      this.abledownload = "";
    }
  },
}
</script>

<style scoped>
.header {
  margin: 5px;
}
</style>